package live.cz.dao;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import live.common.DBHelper;
import live.common.Format;
import live.common.Log4jXmlConfig;
import live.common.PostParam;
import live.common.Verifystring;
import live.cz.entity.Order;
import live.jipiao.dao.XmlFormart;
import live.response.WebServicePay;


/**
 * 查询订单是否成功提交
 */
public class QueryRecord {
	
	private static XmlFormart xf = new XmlFormart();
	
	private static Verifystring vs = new Verifystring();
	
	Logger LOG = Log4jXmlConfig.getInstance().returnLogger(QueryRecord.class);
	
	/**
	 * 判读订单是否已经存在 (19pay)
	 * @param orderNo
	 * @return
	 */
	public Order queryOrder(String orderNo){
		Order order = null;
		DBHelper dh = DBHelper.getInstance();
		dh.setBeanClass(Order.class);
		try {
			order = (Order) dh.query("SELECT * FROM mobile_record WITH(NOLOCK) WHERE orderId='"+orderNo+"'");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		dh.close();
		return order;
	}
	
	@SuppressWarnings("unchecked")
	public boolean searchOrder(String orderNo){
		String result = null;
		boolean flag = true;
		try {
			Map params = new LinkedHashMap();
			params.put("agentid", PostParam.AGENTID);
			params.put("backurl", "");
			params.put("returntype", "2");
			params.put("orderid", orderNo);
			params.put("source", PostParam.SOURCE);
			String sign = DigestUtils.md5Hex(vs.returnVerifystring(params));
			params.put("verifystring",sign);
			result = new WebServicePay()
			.returnResult(PostParam.SEARCH, params);
//			LOG.warn("订单【"+orderNo+"】查询：结果"+result);
			if(Format.getInstance().isNotNullOrEmpty(result)){
			Document document = xf.xmlToDocument(result.trim());
			Element root=document.getRootElement().element("items");
			Element e=null;
			String resultno=null,finishmoney=null;
			for (Iterator i = root.elementIterator();i.hasNext();) {
				e=(Element)i.next();
				if(e.attribute(0).getValue().equals("resultno")){
					resultno=e.attribute(1).getValue();
					if(resultno.equals("1009") || resultno.equals("1")){
						// 订单不存在
						flag=false;
						break;
					}
				}
			}
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}
}
